import errors from './errors';

export default {
    post(options) {
        return new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest()
            xhr.open('POST', options.url)
            xhr.setRequestHeader('Content-Type', 'application/json')
            xhr.setRequestHeader('X-Device', 'Web')
            for (let key in (options.headers || {})) {
                xhr.setRequestHeader(key, options[key])
            }
            xhr.onload = d => {
                try {
                    let data = JSON.parse(xhr.responseText)
                    if(data.stat != 'ok')
                        data.message = errors.match(data.stat);
                    resolve(data)                    
                } catch (e) {
                    reject({stat:'networkError', message:errors.match('networkError')});
                }
            }
            xhr.onerror = e => {
                reject({stat:'networkError', message:errors.match('networkError')});
            }
            xhr.send(JSON.stringify(options.data))
        })
    },

    form(option){
        return new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest()
            xhr.open('POST', option.url)
            xhr.setRequestHeader('Content-Type', 'multipart/form-data')
            xhr.setRequestHeader('X-Device', 'Web')
            for (let key in (option.headers || {})) {
                xhr.setRequestHeader(key, option[key])
            }
    
            if(option.onProgress){
                xhr.addEventListener("progress", function(evt) {
                
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    percentComplete = parseInt(percentComplete * 100);  
                    option.onProgress(percentComplete);  
                }
                else{
                    option.onProgress(50);
                }      
        
                }, false);
            }
          
            xhr.onload = d => {
                try {
                    let data = JSON.parse(xhr.responseText)
                    if(data.stat != 'ok')
                        data.message = errors.match(data.stat);
                    resolve(data)                    
                } catch (e) {
                    reject({stat:'networkError', message:errors.match('networkError')});
                }
            }
            xhr.onerror = e => {
                reject({stat:'networkError', message:errors.match('networkError')});
            }
            xhr.send(option.data)
        })
    }
}